package com.zhentao.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.mapper.WmMaterialMapper;
import com.zhentao.mapper.WmNewsMapper;
import com.zhentao.mapper.WmNewsMaterialMapper;
import com.zhentao.model.common.dtos.PageResponseResult;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.wemedia.dto.WmNewsDownOrUpDto;
import com.zhentao.model.wemedia.dto.WmNewsDto;
import com.zhentao.model.wemedia.dto.WmNewsPageReqDto;
import com.zhentao.model.wemedia.pojo.WmMaterial;
import com.zhentao.model.wemedia.pojo.WmNews;
import com.zhentao.model.wemedia.pojo.WmNewsMaterial;
import com.zhentao.model.wemedia.pojo.WmUser;
import com.zhentao.service.WmNewsAutoScanService;
import com.zhentao.service.WmNewsService;
import com.zhentao.service.WmNewsTaskService;
import com.zhentao.utils.wemedia.WmThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class WmNewsServiceImpl implements WmNewsService {
    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    WmNewsAutoScanService wmNewsAutoScanService;
    @Autowired
    private WmNewsTaskService wmNewsTaskService;
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页参数检查
        dto.checkParam();
        //获取当前登录人的id
        WmUser wmUser = WmThreadLocalUtil.getUser();
        if (wmUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2.分页查询
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        QueryWrapper<WmNews> queryWrapper = new QueryWrapper<>();
        //状态查询
        queryWrapper.lambda().eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        //频道查询
        queryWrapper.lambda().eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        //关键字查询
        queryWrapper.lambda().like(dto.getKeyword() != null, WmNews::getTitle, dto.getKeyword());
        //根据用户查询
        queryWrapper.lambda().eq(WmNews::getUserId, wmUser.getId());
        //按时间倒叙
        queryWrapper.lambda().orderByDesc(WmNews::getCreatedTime);
        //根据时间范围查询
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            queryWrapper.lambda().between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }

        page = wmNewsMapper.selectPage(page, queryWrapper);

        //3.返回结果
        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //1.条件判断
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.保存或者修改文章
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);

        //type数据库使用的是tinyint,0-255,不能使用负数，前端传递的是-1
        if (dto.getType() == -1) {
            dto.setType((short) 4);
        }
        wmNews.setType(dto.getType());

        //补全属性
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setEnable((short) 1);

        //获取文章的封面图片
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            //前端传过来的是json格式，数据库里面的是使用,隔开的图片
            String imgStr = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(imgStr);
        }

        //判断id是否存在，如果不存在执行新增操作，如果已经存在了，执行修改操作；
        //id 是前端页面传递过来的
        if (wmNews.getId() == null) { //新增
            wmNewsMapper.insert(wmNews);
        } else { //修改
            //首先删除文章与素材的关系，再修改
            QueryWrapper<WmNewsMaterial> queryWrapper = new QueryWrapper();
            queryWrapper.lambda().eq(WmNewsMaterial::getNewsId, wmNews.getId());
            wmNewsMaterialMapper.delete(queryWrapper);
            //执行修改操作
            wmNewsMapper.updateById(wmNews);
        }

        if (dto.getType() != 4) {  //封面图片是自己上传的
            //3.绑定关系
            List<String> images = dto.getImages();
            if (images != null && images.size() > 0) {
                //通过查询图片的url获取素材的id
                QueryWrapper<WmMaterial> wmMaterialQueryWrapper = new QueryWrapper<>();
                wmMaterialQueryWrapper.lambda().in(WmMaterial::getUrl, images);
                List<WmMaterial> wmMaterialList = wmMaterialMapper.selectList(wmMaterialQueryWrapper);

                //把素材的id存入list里面
                List<Integer> ids = new ArrayList<>();
                for (WmMaterial wmMaterial : wmMaterialList) {
                    ids.add(wmMaterial.getId());
                }
                //素材与内容进行绑定
                wmNewsMaterialMapper.saveRelations(ids, wmNews.getId(), (short) 0);

            }
        } else { //封面图片需要从内容里面获取
            //把文章中内容的图片给提取出来
            List<Map> maps = JSON.parseArray(dto.getContent(), Map.class);

            List<String> materials = new ArrayList<>();
            for (Map map : maps) {
                if (map.get("type").equals("image")) {
                    String imgUrl = (String) map.get("value");
                    materials.add(imgUrl);
                }
            }


            if (materials != null && materials.size() > 0) {

                //修改封面图片
                String imgs = StringUtils.join(materials, ",");
                wmNews.setImages(imgs);
                wmNewsMapper.updateById(wmNews);

                //绑定关系

                //通过查询图片的url获取素材的id
                QueryWrapper<WmMaterial> wmMaterialQueryWrapper = new QueryWrapper<>();
                wmMaterialQueryWrapper.lambda().in(WmMaterial::getUrl, materials);
                List<WmMaterial> wmMaterialList = wmMaterialMapper.selectList(wmMaterialQueryWrapper);

                //把素材的id存入list里面
                List<Integer> ids = new ArrayList<>();
                for (WmMaterial wmMaterial : wmMaterialList) {
                    ids.add(wmMaterial.getId());
                }
                //素材与内容进行绑定
                wmNewsMaterialMapper.saveRelations(ids, wmNews.getId(), (short) 1);
            }
        }

        //审核文章
        System.out.println("调用审核文章的服务--》进行修改");
        // wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        //        //将原有的直接调用自动审核的接口修改成添加到redis消息队列里面
        wmNewsTaskService.addNewsToTask(wmNews);
//        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    private KafkaTemplate kafkaTemplate;
    /**
     * 文章的上下架
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDownOrUpDto dto) {
        //1.检查参数
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.查询文章
        WmNews wmNews = wmNewsMapper.selectById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        //3.判断文章是否已发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前文章不是发布状态，不能上下架");
        }

        //4.修改文章enable
        wmNews.setEnable(dto.getEnable());
        wmNewsMapper.updateById(wmNews);

        if (wmNews.getArticleId() != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("articleId", wmNews.getArticleId());
            map.put("enable", dto.getEnable());

            //发送消息到kafka
            kafkaTemplate.send("articleDownOrUpTopic", JSON.toJSONString(map));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
